package com.tbynet.jwp.service.impl;

import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.tbynet.jwp.framework.aop.Aop;
import com.tbynet.jwp.framework.core.JwpService;
import com.tbynet.jwp.service.spi.PostImportManager;
import com.tbynet.jwp.service.dto.imports.*;
import com.tbynet.jwp.model.Posts;
import com.tbynet.jwp.repository.spi.PostService;
import com.tbynet.jwp.repository.spi.TermService;
import com.tbynet.jwp.repository.spi.UserService;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 文章导入管理类
 * @ClassName: PostImportManager
 * @Description: 处理文章导入的业务逻辑，支持多种文件格式
 * @Author: 佰亿互联
 * @Date: 2025年11月4日
 *
 * @Copyright: 2025 www.tbynet.com Inc. All rights reserved.
 * 注意: 本内容仅限于内部传阅，禁止外泄以及用于其他的商业目
 */
@Aop(PostImportManager.class)
public class PostImportServiceImpl extends JwpService implements PostImportManager {

    @Inject
    private PostService postService;

    @Inject
    private TermService termService;

    @Inject
    private UserService userService;

    /**
     * 导入文章
     * @param file 导入文件
     * @param fileType 文件类型
     * @param config 导入配置
     * @return 导入结果
     */
    public ImportResult importPosts(File file, String fileType, ImportConfig config) {
        ImportResult result = new ImportResult();

        try {
            switch (fileType.toLowerCase()) {
                case "csv":
                    result = importFromCsv(file, config);
                    break;
                case "xml":
                case "wordpress":
                    result = importFromWordPressXml(file, config);
                    break;
                case "json":
                    result = importFromJson(file, config);
                    break;
                default:
                    result.setSuccess(false);
                    result.setErrorMessage("不支持的文件格式: " + fileType);
                    break;
            }
        } catch (Exception e) {
            log.error("导入文章失败", e);
            result.setSuccess(false);
            result.setErrorMessage("导入失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 从CSV文件导入文章
     */
    private ImportResult importFromCsv(File file, ImportConfig config) throws IOException {
        ImportResult result = new ImportResult();

        try (FileReader reader = new FileReader(file);
             CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader())) {

            for (CSVRecord record : csvParser) {
                try {
                    Posts post = createPostFromCsvRecord(record, config);

                    // 在事务中保存文章
                    boolean success = Db.tx(new IAtom() {
                        @Override
                        public boolean run() throws SQLException {
                            return savePostWithTransaction(post, config);
                        }
                    });

                    if (success) {
                        result.incrementImportedCount();
                    } else {
                        result.addError("文章保存失败: " + record.get("title"));
                    }

                } catch (Exception e) {
                    log.error("处理CSV记录失败", e);
                    result.addError("处理文章失败: " + e.getMessage());
                }
            }
        }

        result.setSuccess(true);
        return result;
    }

    /**
     * 从WordPress XML文件导入文章
     */
    private ImportResult importFromWordPressXml(File file, ImportConfig config) throws Exception {
        ImportResult result = new ImportResult();

        String xmlContent = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
        Document document = DocumentHelper.parseText(xmlContent);
        Element root = document.getRootElement();
        Element channel = root.element("channel");

        if (channel == null) {
            throw new Exception("无效的WordPress导出文件");
        }

        List<Element> items = channel.elements("item");
        for (Element item : items) {
            try {
                String postType = getElementText(item, "wp:post_type");
                if (!"post".equals(postType)) {
                    continue; // 只处理文章类型
                }

                Posts post = createPostFromXmlElement(item, config);

                // 在事务中保存文章
                boolean success = Db.tx(new IAtom() {
                    @Override
                    public boolean run() throws SQLException {
                        return savePostWithTransaction(post, config);
                    }
                });

                if (success) {
                    result.incrementImportedCount();

                    // 处理分类和标签
                    if (config.isImportCategories() || config.isImportTags()) {
                        importCategoriesAndTagsFromXml(post.getID(), item, config);
                    }
                } else {
                    result.addError("文章保存失败: " + getElementText(item, "title"));
                }

            } catch (Exception e) {
                log.error("处理XML项目失败", e);
                result.addError("处理文章失败: " + e.getMessage());
            }
        }

        result.setSuccess(true);
        return result;
    }

    /**
     * 从JSON文件导入文章
     */
    private ImportResult importFromJson(File file, ImportConfig config) {
        // TODO: 实现JSON导入逻辑
        ImportResult result = new ImportResult();
        result.setSuccess(true);
        result.setErrorMessage("JSON导入功能暂未实现");
        return result;
    }

    /**
     * 从CSV记录创建文章对象
     */
    private Posts createPostFromCsvRecord(CSVRecord record, ImportConfig config) {
        Posts post = new Posts();

        // 设置文章基本信息
        post.setPostTitle(getCsvValue(record, "title", ""));
        post.setPostContent(getCsvValue(record, "content", ""));
        post.setPostExcerpt(getCsvValue(record, "excerpt", ""));
        post.setPostStatus(getCsvValue(record, "status", config.getDefaultStatus()));
        post.setPostType(Posts.POST_TYPE_POST);
        post.setPostAuthor(new BigInteger(config.getAuthor()));
        post.setPostDate(getCsvDate(record, "date", new Date()));
        post.setPostDateGmt(getCsvDate(record, "date_gmt", new Date()));
        post.setPostModified(new Date());
        post.setPostModifiedGmt(new Date());
        post.setCommentStatus(getCsvValue(record, "comment_status", "open"));
        post.setPingStatus(getCsvValue(record, "ping_status", "open"));

        return post;
    }

    /**
     * 从XML元素创建文章对象
     */
    private Posts createPostFromXmlElement(Element item, ImportConfig config) {
        Posts post = new Posts();

        // 设置文章基本信息
        post.setPostTitle(getElementText(item, "title"));
        post.setPostContent(getElementText(item, "content:encoded"));
        post.setPostExcerpt(getElementText(item, "excerpt:encoded"));
        post.setPostStatus(getElementText(item, "wp:status"));
        post.setPostType(Posts.POST_TYPE_POST);
        post.setPostAuthor(new BigInteger(config.getAuthor()));
        post.setPostDate(parseWordPressDate(getElementText(item, "wp:post_date")));
        post.setPostDateGmt(parseWordPressDate(getElementText(item, "wp:post_date_gmt")));
        post.setPostModified(new Date());
        post.setPostModifiedGmt(new Date());
        post.setCommentStatus(getElementText(item, "wp:comment_status"));
        post.setPingStatus(getElementText(item, "wp:ping_status"));
        post.setPostName(getElementText(item, "wp:post_name"));

        return post;
    }

    /**
     * 在事务中保存文章
     */
    private boolean savePostWithTransaction(Posts post, ImportConfig config) throws SQLException {
        if (config.isDryRun()) {
            return true; // 干运行模式，不实际保存
        }

        // 在事务中保存文章
        return Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                // 检查是否更新已存在的文章
                if (config.isUpdateExisting()) {
                    Posts existingPost = postService.findPostByTitle(post.getPostTitle());
                    if (existingPost != null) {
                        post.setID(existingPost.getID());
                        return postService.update(post);
                    }
                }

                return postService.save(post);
            }
        });
    }

    /**
     * 从XML导入分类和标签
     */
    private void importCategoriesAndTagsFromXml(BigInteger postId, Element item, ImportConfig config) {
        try {
            // 处理分类
            if (config.isImportCategories()) {
                List<Element> categories = item.elements("category");
                for (Element category : categories) {
                    String domain = category.attributeValue("domain");
                    if ("category".equals(domain)) {
                        String categoryName = category.getTextTrim();
                        // 调用TermService处理分类
                        termService.getOrCreateTerm(categoryName, "category");
                    }
                }
            }

            // 处理标签
            if (config.isImportTags()) {
                List<Element> categories = item.elements("category");
                for (Element category : categories) {
                    String domain = category.attributeValue("domain");
                    if ("post_tag".equals(domain)) {
                        String tagName = category.getTextTrim();
                        // 调用TermService处理标签
                        termService.getOrCreateTerm(tagName, "post_tag");
                    }
                }
            }
        } catch (Exception e) {
            log.error("导入分类和标签失败", e);
        }
    }

    // 辅助方法保持不变，从原Controller中迁移...
    private String getCsvValue(CSVRecord record, String column, String defaultValue) {
        try {
            return record.get(column);
        } catch (IllegalArgumentException e) {
            return defaultValue;
        }
    }

    private Date getCsvDate(CSVRecord record, String column, Date defaultValue) {
        try {
            String dateStr = record.get(column);
            return parseWordPressDate(dateStr);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    private String getElementText(Element parent, String childName) {
        Element child = parent.element(childName);
        return child != null ? child.getText() : "";
    }

    private Date parseWordPressDate(String dateStr) {
        if (dateStr == null || dateStr.trim().isEmpty()) {
            return new Date();
        }
        try {
            // 简化的日期解析，实际项目中应该使用更健壮的解析方法
            return new Date(); // 这里需要实现具体的日期解析逻辑
        } catch (Exception e) {
            return new Date();
        }
    }

    /**
     * 获取导入统计信息
     */
    public ImportStatistics getImportStatistics() {
        ImportStatistics stats = new ImportStatistics();

        try {
            // 查询数据库获取统计信息
            Record totalRecord = Db.findFirst("SELECT COUNT(*) as total FROM wp_import_log");
            Record successRecord = Db.findFirst("SELECT COUNT(*) as success FROM wp_import_log WHERE status = 'success'");
            Record lastImportRecord = Db.findFirst("SELECT MAX(import_time) as last_time FROM wp_import_log");
            Record postsRecord = Db.findFirst("SELECT COUNT(*) as total_posts FROM wp_posts WHERE post_type = 'post'");

            stats.setTotalImports(totalRecord != null ? totalRecord.getInt("total") : 0);
            stats.setSuccessfulImports(successRecord != null ? successRecord.getInt("success") : 0);
            stats.setFailedImports(stats.getTotalImports() - stats.getSuccessfulImports());
            stats.setLastImportTime(lastImportRecord != null ? lastImportRecord.getDate("last_time") : null);
            stats.setTotalImportedPosts(postsRecord != null ? postsRecord.getInt("total_posts") : 0);
            stats.setMostUsedFormat("CSV"); // 简化实现

        } catch (Exception e) {
            log.error("获取导入统计信息失败", e);
        }

        return stats;
    }

    /**
     * 获取模板路径
     */
    public String getTemplatePath(String templateType) {
        switch (templateType.toLowerCase()) {
            case "csv":
                return "/templates/post_import_template.csv";
            case "xml":
                return "/templates/wordpress_export_template.xml";
            default:
                return null;
        }
    }

    /**
     * 获取导入进度
     */
    public ImportProgress getImportProgress(String taskId) {
        // 简化实现 - 实际项目中应该从缓存或数据库中获取进度
        ImportProgress progress = new ImportProgress();
        progress.setProgress(100);
        progress.setStatus("completed");
        progress.setMessage("导入已完成");
        progress.setTaskId(taskId);
        return progress;
    }

    /**
     * 获取导入历史
     */
    public ImportHistory getImportHistory(int page, int size) {
        List<ImportRecord> records = new ArrayList<>();

        try {
            // 查询导入日志
            List<Record> dbRecords = Db.paginate(page, size, "SELECT *", "FROM wp_import_log ORDER BY import_time DESC").getList();

            for (Record dbRecord : dbRecords) {
                ImportRecord record = new ImportRecord();
                record.setId(dbRecord.getStr("id"));
                record.setFileName(dbRecord.getStr("file_name"));
                record.setFileType(dbRecord.getStr("file_type"));
                record.setImportedCount(dbRecord.getInt("imported_count"));
                record.setErrorCount(dbRecord.getInt("error_count"));
                record.setImportTime(dbRecord.getDate("import_time"));
                record.setStatus(dbRecord.getStr("status"));
                record.setOperator(dbRecord.getStr("operator"));
                records.add(record);
            }

            int totalCount = Db.queryInt("SELECT COUNT(*) FROM wp_import_log");

            return new ImportHistory(records, totalCount, page, size);

        } catch (Exception e) {
            log.error("获取导入历史失败", e);
            return new ImportHistory(records, 0, page, size);
        }
    }

//  -- 导入日志表
//  CREATE TABLE IF NOT EXISTS `wp_import_log` (
//      `id` varchar(100) NOT NULL,
//      `file_name` varchar(255) NOT NULL,
//      `file_type` varchar(20) NOT NULL,
//      `imported_count` int(11) NOT NULL DEFAULT '0',
//      `error_count` int(11) NOT NULL DEFAULT '0',
//      `import_time` datetime NOT NULL,
//      `status` varchar(20) NOT NULL,
//      `operator` varchar(100) NOT NULL,
//      `error_message` text,
//      PRIMARY KEY (`id`),
//      KEY `import_time` (`import_time`),
//      KEY `status` (`status`)
//  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
}